import {
	loginStatusVerify
} from '@/utils/index.js'

import app from '@/main.js';

export default class Http {
	requestNum = 0
	token = ''
	constructor(baseUrl = '') {
		this.baseUrl = baseUrl
	}
	print() {
		console.log(this.baseUrl, this.requestNum, this.token)
	}
	
	// 请求发起之前
	beforeRequest() {
		this.requestNum += 1
		if (this.isLoginStatusVerify) {
			this.token = loginStatusVerify()
		}
	}
	
	// 请求结束后
	afterRequest(flag) {
		setTimeout(res => {
			this.requestNum -= 1
			if (this.requestNum === 0) {
				uni.hideLoading()
			}
		}, 0)
		if (flag) {
			this.requestSuccess()
		} else {
			this.requestFail()
		}
	}
	
	// 发起请求成功
	requestSuccess() {

	}
	
	// 发起请求失败
	requestFail() {
		// setTimeout(res => {
		uni.showToast({
			title: '请求失败！请检查网络！',
			icon: 'none',
			duration: 2000,
			position: 'top',
		});
		// }, 300)
	}

	get(url = '', defineData = {}, isShowLoading = true, isLoginStatusVerify = true) {
		return (data = {}) => {
			this.beforeRequest()
			this.showLoading(isShowLoading)
			return new Promise((resolve, reject) => {
				uni.request({
					method: 'GET',
					url: this.baseUrl + url,
					header: {
						Authorization: this.token,
						// ...header
					},
					data: {
						...defineData,
						...data
					},
					success: (res) => {
						this.afterRequest(true)
						resolve(res.data)
					},
					fail: (err) => {
						this.afterRequest(false)
						reject(err)
					}
				});
			})
		}
	}

	post(url = '', defineData = {}, isShowLoading = true, isLoginStatusVerify = true) {
		return (data = {}) => {
			this.beforeRequest()
			this.showLoading(isShowLoading)
			return new Promise((resolve, reject) => {
				uni.request({
					method: 'POST',
					url: this.baseUrl + url,
					header: {
						Authorization: this.token,
						// ...header
					},
					data: {
						...defineData,
						...data
					},
					success: (res) => {
						this.afterRequest(true)
						resolve(res.data)
					},
					fail: (err) => {
						this.afterRequest(false)
						reject(err)
					}
				});
			})
		}
	}

	showLoading(isShowLoading) {
		if (isShowLoading && this.requestNum === 1) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}
	}
}
